package com.ice.work.moment.socket.service.impl;

import com.honeybee.cloud.framework.base.exception.business.BaseBizException;
import com.honeybee.cloud.framework.common.constant.CommonMessageConstant;
import com.honeybee.cloud.framework.common.enums.DataStatusEnum;
import com.ice.work.moment.facade.socket.dto.PushAuthorizationDTO;
import com.ice.work.moment.facade.socket.mapper.PushAuthorizationConvertMapper;
import com.ice.work.moment.facade.socket.model.PushAuthorization;
import com.ice.work.moment.facade.socket.params.LoginParam;
import com.ice.work.moment.socket.dao.authorization.PushAuthorizationRepository;
import com.ice.work.moment.socket.service.IPushAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.Objects;

/**
 * @Description 凭证
 * @Author DELL
 * @Create 2019-04-22
 * @Since 1.0.0
 */
@Service
public class PushAuthorizationServiceImpl implements IPushAuthorizationService {
    @Autowired
    private PushAuthorizationRepository pushAuthorizationRepository;

    @Override
    public Boolean add(PushAuthorization pushAuthorization) throws BaseBizException {
        Assert.notNull(pushAuthorization, "pushAuthorization:" + CommonMessageConstant.PARAM_IS_NULL);
        pushAuthorization.setCreateAt(new Date());
        pushAuthorization.setDataStatus(DataStatusEnum.VALID.key);
        return pushAuthorizationRepository.save(pushAuthorization);
    }

    @Override
    public Boolean delete(Long id) throws BaseBizException {
        Assert.notNull(id, CommonMessageConstant.PARAM_IS_NULL);
        PushAuthorization pushAuthorization = new PushAuthorization();
        pushAuthorization.setId(id);
        pushAuthorization.setDataStatus(DataStatusEnum.INVALID.key);
        return pushAuthorizationRepository.updateById(pushAuthorization);
    }

    @Override
    public PushAuthorizationDTO login(LoginParam param) throws BaseBizException {
        Assert.notNull(param, CommonMessageConstant.PARAM_IS_NULL);
        PushAuthorization pushAuthorization = pushAuthorizationRepository.findByAccessKeyAndAccessSecretAndDeviceTypeAndDataStatus(param);
        if (Objects.isNull(pushAuthorization)) {
            //授权凭证不正确
        }
        Date nowDate = new Date();
        boolean expire = Objects.nonNull(pushAuthorization.getExpireAt()) && pushAuthorization.getExpireAt().getTime() < nowDate.getTime();
        if (expire) {
            //凭证已过期
        }
        return PushAuthorizationConvertMapper.INSTANCE.toDTO(pushAuthorization);
    }
}
